//
//  Helper.swift
//  mac-wky
//
//  Created by Apple on 2018/2/7.
//  Copyright © 2018年 Apple. All rights reserved.
//

import Foundation

class Helper {
    
    struct ParamsRst {
        var params: [String: String]
        var paramsStr: String
        var paramsData: Data
    }
    
    /// 加密密码
    ///
    /// - Parameter pass: 密码
    /// - Returns: 加密后密码
    static func cryptoPass(_ pass: String) -> String {
        if pass.isEmpty { return "" }
        
        var passMD5 = pass.md5()
        let ab = passMD5[2]
        let ba = passMD5[8]
        let cd = passMD5[17]
        let dc = passMD5[27]
        
        passMD5[2] = ba
        passMD5[8] = ab
        passMD5[17] = dc
        passMD5[27] = cd
        return passMD5.md5()
    }
    
    static func getParams(_ baseParams: [String: String], isGet: Bool = false) -> ParamsRst {
        // 结果类型为 [String: String]
        var params = [String: String]()
        // 1、拼接参数
        var list = [String]()
        baseParams.forEach { k, v in
            let val = k == "pwd" ? cryptoPass(v) : v
            params[k] = val
            list.append("\(k)=\(val)")
        }
        
        // 2、对参数进行排序
        list.sort()
        
        // 3.1、get参数
        var gstr = ""
        list.forEach { v in
            gstr += v
            if let last = list.last, v == last { return }
            gstr += "&"
        }
        
        // 3.2、post参数
        let sessionid = App.getCookie(name: "sessionid")
        let pstr = "\(gstr)&key=\(sessionid)"
        if !isGet { params["key"] = sessionid }
        
        // 4、加签，不管是get还是post，均使用pstr参数进行加签
        let sign = pstr.md5()
        
        // 5、生成最终参数
        let paramsStr = "\(isGet ? gstr : pstr)&sign=\(sign)"
        params["sign"] = sign
        let paramsData = paramsStr.data(using: .utf8)!
                
        // 6、返回最终参数
        return ParamsRst(params: params, paramsStr: paramsStr, paramsData: paramsData)
    }
}


